// pages/addressList/addressList.js
// pages/addressList/addressList.js
Page({
    data: {
        addressList: [], // 地址列表
        isFromSelect: false, // 是否从选择地址页面跳转过来
        selectedAddressId: '' // 已选择的地址ID
    },

    onLoad(options) {
        console.log(options);
        // 检查是否从选择地址页面跳转过来
        if (options.isFromSelect) {
            this.setData({
                isFromSelect: true
            });

            // 如果有已选择的地址ID，标记已选择
            if (options.selectedAddressId) {
                this.setData({
                    selectedAddressId: options.selectedAddressId
                });
            }
        }

        // 获取收货地址列表
        this.getAddressList();
    },

    onShow() {
        // 页面显示时重新获取地址列表，确保数据最新
        this.getAddressList();
    },

    // 获取收货地址列表
    getAddressList() {
        wx.showLoading({
            title: '加载中...',
        });

        // 获取用户ID
        const userId = wx.getStorageSync('userInfo')._id;

        if (!userId) {
            wx.hideLoading();
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            return;
        }

        // 调用云函数获取地址列表
        wx.cloud.callFunction({
            name: 'address',
            data: {
                action: 'list',
                userId: userId
            }
        }).then(res => {
            console.log(res);
            wx.hideLoading();

            if (res.result.success) {
                this.setData({
                    addressList: res.result.addressList
                });
            } else {
                wx.showToast({
                    title: res.result.message || '获取地址失败',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.hideLoading();
            console.error('获取地址列表失败:', err);
            wx.showToast({
                title: '获取地址失败，请重试',
                icon: 'none'
            });
        });
    },

    // 选择地址
    selectAddress(e) {

        if (!this.data.isFromSelect) return;
        console.log(e);
        const addressId = e.currentTarget.dataset.addressid;
        this.setData({
            selectedAddressId: addressId
        });

        // 标记地址为已选择
        const addressList = this.data.addressList.map(item => {
            if (item._id === addressId) {
                return {
                    ...item,
                    isSelected: true
                };
            }
            return {
                ...item,
                isSelected: false
            };
        });

        this.setData({
            addressList: addressList
        });
    },

    // 确认选择地址
    confirmSelect() {
        if (!this.data.selectedAddressId) {
            wx.showToast({
                title: '请选择收货地址',
                icon: 'none'
            });
            return;
        }
        // 获取全局回调函数并执行
        const callback = getApp().addressSelectCallback;
        if (typeof callback === 'function') {
            callback(this.data.selectedAddressId);
        }

        wx.navigateBack();

    },
    // 删除地址
    deleteAddress(e) {
        const addressId = e.currentTarget.dataset.addressid;
        const addressList = this.data.addressList;
        const address = addressList.find(item => item._id === addressId);

        wx.showModal({
            title: '提示',
            content: '确定要删除该收货地址吗？',
            success: (res) => {
                if (res.confirm) {
                    wx.showLoading({
                        title: '删除中...',
                    });

                    // 调用云函数删除地址
                    wx.cloud.callFunction({
                        name: 'address',
                        data: {
                            action: 'delete',
                            userId: wx.getStorageSync('userInfo')._id,
                            addressId: addressId
                        }
                    }).then(res => {
                        wx.hideLoading();

                        if (res.result.success) {
                            wx.showToast({
                                title: '删除成功',
                                icon: 'success'
                            });

                            // 如果删除的是默认地址，将其他地址设为默认
                            if (address.isDefault) {
                                const firstAddress = addressList.find(item => item._id !== addressId);
                                if (firstAddress) {
                                    wx.cloud.callFunction({
                                        name: 'address',
                                        data: {
                                            action: 'setDefault',
                                            userId: wx.getStorageSync('userInfo')._id,
                                            addressId: firstAddress._id
                                        }
                                    }).then(() => {
                                        // 重新获取地址列表
                                        this.getAddressList();
                                    }).catch(err => {
                                        console.error('设置默认地址失败:', err);
                                        this.getAddressList();
                                    });
                                } else {
                                    this.getAddressList();
                                }
                            } else {
                                this.getAddressList();
                            }
                        } else {
                            wx.showToast({
                                title: res.result.message || '删除失败',
                                icon: 'none'
                            });
                        }
                    }).catch(err => {
                        wx.hideLoading();
                        console.error('删除地址失败:', err);
                        wx.showToast({
                            title: '删除失败，请重试',
                            icon: 'none'
                        });
                    });
                }
            }
        });
    },
    // 新增
    toAddRouter() {
        wx.navigateTo({
            url: '/pages/addAddress/addAddress'
        });
    },
    // 编辑
    editAddress(e) {
        console.log(e);
        const addressId = e.currentTarget.dataset.addressid;
        wx.navigateTo({
            url: `/pages/addressList/editAddress/index?addressId=${addressId}`
        });
    }
});